package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.MaritimeConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DeviceStatus;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.IOUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.my.data.FileRequest;
import com.ruoyi.system.domain.MrDevice;
import com.ruoyi.system.domain.vo.MrDeviceVO;
import com.ruoyi.system.service.IMrDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;

/**
 * 设备管理Controller
 *
 * @author ruoyi
 * @date 2022-11-18
 */
@RestController
@RequestMapping("/system/device")
public class MrDeviceController extends BaseController {
    @Autowired
    private IMrDeviceService mrDeviceService;

    /**
     * 查询设备管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(MrDevice mrDevice) {
        startPage();
        List<MrDevice> list = mrDeviceService.selectMrDeviceList(mrDevice);
        return getDataTable(list);
    }


    @GetMapping("/listDevs")
    public AjaxResult listDevs(MrDevice mrDevice) {
        mrDevice.setStatus(DeviceStatus.ACTIVE.getValue());
        return success(mrDeviceService.listDevs(mrDevice));
    }

    /**
     * 查询设备管理列表
     */
    @GetMapping("/listByDeptIdAndModality")
    public TableDataInfo listByDeptIdAndModality(MrDevice mrDevice) {
        startPage();
        List<MrDeviceVO> list = mrDeviceService.listByDeptIdAndModality(mrDevice);
        return getDataTable(list);
    }

    @GetMapping("/queryTestMuteRecord")
    public AjaxResult queryTestMuteRecord(MrDevice mrDevice) {
        mrDevice.setStatus(DeviceStatus.ACTIVE.getValue());
        return success(mrDeviceService.queryTestMuteRecord(mrDevice));
    }

    @GetMapping("/byCategory")
    public AjaxResult byCategory(MrDevice mrDevice) {
        mrDevice.setStatus(DeviceStatus.ACTIVE.getValue());
        return success(mrDeviceService.byCategory(mrDevice));
    }

    /**
     * 蜂鸣器处理
     */
    @GetMapping("/mute/{writeValue}")
    public void mute(@PathVariable("writeValue") boolean writeValue) {
        mrDeviceService.mute(writeValue, MaritimeConstants.BUZZER);
    }

    /**
     * 输出处理
     */
    @GetMapping("/mute/{writeValue}/{outputSource}")
    public void mute(@PathVariable("writeValue") boolean writeValue, @PathVariable("outputSource") String outputSource) {
        mrDeviceService.muteBySystemId(writeValue, outputSource);
    }

    /**
     * 导出设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:device:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MrDevice mrDevice) {
        List<MrDevice> list = mrDeviceService.selectMrDeviceList(mrDevice);
        ExcelUtil<MrDevice> util = new ExcelUtil<MrDevice>(MrDevice.class);
        util.exportExcel(response, list, "设备管理数据");
    }

    @Log(title = "设备管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:device:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MrDevice> util = new ExcelUtil<>(MrDevice.class);
        List<MrDevice> deviceList = util.importExcel(file.getInputStream());
        String openName = getUsername();
        String message = mrDeviceService.importDevice(deviceList, updateSupport, openName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<MrDevice> util = new ExcelUtil<>(MrDevice.class);
        util.importTemplateExcel(response, "设备数据");
    }


    /**
     * 打印设备监测点数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:device:printData')")
    @Log(title = "设备管理数据", businessType = BusinessType.OTHER)
    @PostMapping("/printData")
    public void printData(HttpServletResponse response, @RequestBody MrDevice mrDevice) {
        mrDeviceService.printData(response, mrDevice);
    }

    /**
     * 获取设备管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return success(mrDeviceService.selectMrDeviceByDeviceId(deviceId));
    }

    /**
     * 新增设备管理
     */
    @PreAuthorize("@ss.hasPermi('system:device:add')")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MrDevice mrDevice) {
        mrDevice.setCreateBy(getUsername());
        return toAjax(mrDeviceService.insertMrDevice(mrDevice));
    }

    /**
     * 修改设备管理
     */
    @PreAuthorize("@ss.hasPermi('system:device:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MrDevice mrDevice) {
        mrDevice.setUpdateBy(getUsername());
        return toAjax(mrDeviceService.updateMrDevice(mrDevice));
    }

    /**
     * 删除设备管理
     */
    @PreAuthorize("@ss.hasPermi('system:device:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceId}")
    public AjaxResult remove(@PathVariable Long deviceId) {
        return toAjax(mrDeviceService.deleteMrDeviceByDeviceId(deviceId));
    }

    @GetMapping("/download")
    public void download(FileRequest request) throws Exception {
        downloadTask(request);
    }

    private void downloadTask(FileRequest request) throws Exception {
        ServletOutputStream outputStream = null;
        InputStream inputStream;
        try {
            File file = new File(request.getDownloadId() + "/" + request.getFileName());

            inputStream = Files.newInputStream(file.toPath());

            HttpServletResponse response = ServletUtils.getResponse();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(request.getFileName(), "utf-8"));
            outputStream = response.getOutputStream();

            IOUtils.copyBytes(inputStream, outputStream, 4096, false);

            if (file.exists()) {
                file.delete();
            }
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
            } catch (Exception ignored) {
            }
        }
    }


}
